﻿using System;
using System.IO;

namespace SlamCms.Configuration
{
	public class ConfigurationManager
	{
		private static string _solutionRootFolderPath;
		private static SolutionConfiguration _solutionConfiguration;
		private static EnvironmentConfiguration _environmentConfiguration;

		public static string ConfigurationFolderPath
		{
			get
			{	
				var configurationDirectory = new DirectoryInfo(Path.Combine(SolutionRootFolderPath, "config"));
				if (!configurationDirectory.Exists && !Directory.Exists(configurationDirectory.FullName))
				{
					throw new DirectoryNotFoundException("Configuration directory not found.  SLAM CMS Configuration expects a configuration directory to exist at " + configurationDirectory.FullName);
				}
				return configurationDirectory.FullName;
			}
		}

		public static string SolutionRootFolderPath
		{
			get
			{
				if (String.IsNullOrEmpty(_solutionRootFolderPath))
				{
					var baseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
					var rootDirectory = FindSolutionDirectory(baseDirectory);
					if (rootDirectory == null)
					{
						rootDirectory = baseDirectory.Parent;
					}

					if (!rootDirectory.Exists)
					{
						throw new DirectoryNotFoundException("Solution root directory not found.  SLAM CMS Configuration expects this application's solution directory to exist at " + rootDirectory.FullName);
					}

					_solutionRootFolderPath = rootDirectory.FullName;
				}
				return _solutionRootFolderPath;
			}
		}

		public static SolutionConfiguration Solution
		{
			get
			{
				if (_solutionConfiguration == null)
				{
					_solutionConfiguration = new SolutionConfiguration();
				}

				return _solutionConfiguration;
			}
		}

		public static EnvironmentConfiguration Environment
		{
			get
			{
				if (_environmentConfiguration == null)
				{
					_environmentConfiguration = new EnvironmentConfiguration();
				}

				return _environmentConfiguration;
			}
		}

		private static DirectoryInfo FindSolutionDirectory(DirectoryInfo currentDirectory)
		{
			DirectoryInfo solutionDirectory = null;
			currentDirectory = currentDirectory.Parent;

			if (currentDirectory == null)
				throw new DirectoryNotFoundException("There's no config folder for the solution. Please check that you have the proper config folder and config files for the solution");

			if (currentDirectory.Exists)
			{
				foreach (var childDirectory in currentDirectory.GetDirectories())
				{
					if (childDirectory.Name.Equals("config", StringComparison.OrdinalIgnoreCase) && solutionDirectory == null)
					{
						solutionDirectory = currentDirectory;
						break;
					}
				}

				if (solutionDirectory == null)
				{
					solutionDirectory = FindSolutionDirectory(currentDirectory);
				}
			}

			return solutionDirectory;
		}
	}
}
